<template>
  <div>
    <el-form-item label="服务号">
      <el-button type="primary" @click="handleAdd" link>添加账号</el-button>
    </el-form-item>
    <div class="friend-editor">
      <el-tree
        ref="treeRef"
        :data="editorForm.service.value"
        draggable
        node-key="id"
        expand-all
        :props="treeProps"
        :allow-drop="allowDrop"
        :allow-drag="allowDrag"
      >
        <template #default="{ node, data }">
          <div class="tree-node" @mouseenter="activeNode = data" @mouseleave="activeNode = null">
            <span class="node-label">{{ data.name }}</span>
            <div v-show="activeNode && activeNode.id === node.data.id" class="node-btns">
              <el-icon :size="12" @click.stop="handleAddChild(node, data)">
                <Plus />
              </el-icon>
              <el-icon :size="12" @click.stop="handleDelete(node, data)">
                <Delete />
              </el-icon>
              <el-icon :size="12" @click.stop="handleEdit(data, node)">
                <Edit />
              </el-icon>
            </div>
          </div>
        </template>
      </el-tree>
      <el-dialog v-model="dialogShow" :title="dialogTitle" width="500px" @close="resetForm">
        <el-form ref="formRef" :model="form" label-width="80px" label-position="right">
          <el-form-item label="名称" prop="name">
            <el-input v-model="form.name" placeholder="请输入平台名称"></el-input>
          </el-form-item>
          <el-form-item label="图标" prop="icon">
            <IconSelect v-model:currentIcon="form.icon" />
          </el-form-item>
          <el-form-item label="logo" prop="logo">
            <div class="form-img" @click="handleUpload('logo')">
              <div class="has-img" v-if="form.logo">
                <img :src="form.logo" alt="" />
                <span @click.stop="handleRemoveImg('logo')">
                  <el-icon>
                    <Delete />
                  </el-icon>
                </span>
              </div>
              <el-icon v-else>
                <Plus />
              </el-icon>
            </div>
          </el-form-item>
          <el-form-item label="二维码" prop="qrCode">
            <div class="form-img" @click="handleUpload('qrCode')">
              <div class="has-img" v-if="form.qrCode">
                <img :src="form.qrCode" alt="" />
                <span @click.stop="handleRemoveImg('qrCode')">
                  <el-icon>
                    <Delete />
                  </el-icon>
                </span>
              </div>
              <el-icon v-else>
                <Plus />
              </el-icon>
            </div>
          </el-form-item>
        </el-form>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="dialogShow = false">取消</el-button>
            <el-button type="primary" @click="handleConfirm">确认</el-button>
          </span>
        </template>
      </el-dialog>
      <FilesUpload v-model:showDialog="showBackImageUpload" :limit="1" @getFileList="handleGetCoverImg" />
    </div>
  </div>
</template>

<script setup>
import { ref, inject, reactive, watch, computed } from 'vue'
import { Edit, Delete, Plus } from '@element-plus/icons-vue'

const { editorForm, backUpdate } = inject('commonForm')
watch(() => editorForm.value.service, () => {
  backUpdate()
}, { deep: true })

// 树相关变量
const treeRef = ref(null)
const treeProps = ref({
  label: 'name',
  children: 'children'
})
const activeNode = ref(null)

// 对话框相关
const dialogShow = ref(false)
const optionWay = ref('add')
const currentNode = ref(null)
const currentParent = ref(null)
const formRef = ref(null)

// 默认表单
const defaultForm = reactive({
  id: '',
  name: '',
  logo: '',
  qrCode: '',
  icon: '',
  children: []
})

const form = ref(Object.assign({}, defaultForm))

const dialogTitle = computed(() => {
  if (optionWay.value === 'add') {
    return '添加服务号'
  } else if (optionWay.value === 'addChild') {
    return '添加子服务号'
  } else {
    return '编辑服务号'
  }
})

// 添加根节点
const handleAdd = () => {
  optionWay.value = 'add'
  currentNode.value = null
  currentParent.value = null
  dialogShow.value = true
}

// 添加子节点
const handleAddChild = (node, data) => {
  optionWay.value = 'addChild'
  currentNode.value = node
  currentParent.value = data
  dialogShow.value = true
}

// 编辑节点
const handleEdit = (data, node) => {
  optionWay.value = 'edit'
  currentNode.value = node
  form.value = JSON.parse(JSON.stringify(data))
  dialogShow.value = true
}

// 删除节点
const handleDelete = (node, data) => {
  const parent = node.parent
  const children = parent.data.children || parent.data
  const index = children.findIndex(d => d.id === data.id)
  children.splice(index, 1)
}

// 表单确认
const handleConfirm = () => {
  // 添加唯一ID
  if (!form.value.id) {
    form.value.id = Date.now().toString()
  }
  
  // 确保有children数组
  if (!form.value.children) {
    form.value.children = []
  }

  const newItem = JSON.parse(JSON.stringify(form.value))
  
  if (optionWay.value === 'edit') {
    // 编辑现有节点
    const parent = currentNode.value.parent
    const children = parent.data.children || parent.data
    const index = children.findIndex(d => d.id === currentNode.value.data.id)
    if (index !== -1) {
      // 保留原来的children
      newItem.children = children[index].children || []
      children.splice(index, 1, newItem)
    }
  } else if (optionWay.value === 'addChild') {
    // 添加子节点
    if (!currentParent.value.children) {
      currentParent.value.children = []
    }
    currentParent.value.children.push(newItem)
  } else {
    // 添加根节点
    editorForm.value.service.value.push(newItem)
  }
  
  dialogShow.value = false
}

// 拖拽相关
const allowDrop = () => {
  return true // 允许所有放置位置
}

const allowDrag = () => {
  return true // 允许所有节点拖拽
}

// 重置表单
const resetForm = () => {
  if (formRef.value) {
    formRef.value.clearValidate()
  }
  form.value = Object.assign({}, defaultForm)
}

// 图片上传相关
const showBackImageUpload = ref(false)
const curField = ref('')

const handleUpload = (key) => {
  curField.value = key
  showBackImageUpload.value = true
}

const handleGetCoverImg = imgList => {
  form.value[curField.value] = imgList[0].url
}

// 移除图片
const handleRemoveImg = (key) => {
  form.value[key] = ''
}
</script>

<style lang="scss" scoped>
.friend-editor {
  margin-top: -15px;
  width: 100%;
}

:deep(.el-tree-node__content) {
  .el-tree-node__label {
    width: 100%;
  }
}

.tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 8px;
  height: 32px;
  
  .node-label {
    font-size: 12px;
  }
  
  .node-btns {
    display: flex;
    align-items: center;
    
    .el-icon {
      margin-left: 8px;
      cursor: pointer;
      
      &:hover {
        color: $mainColor;
      }
    }
  }
}

.form-img {
  height: 100px;
  width: 150px;
  border: 1px dashed $borderColor;
  cursor: pointer;
  display: flex;
  justify-content: center;
  align-items: center;

  .has-img {
    height: 100%;
    width: 100%;
    position: relative;
    display: flex;
    justify-content: center;
    align-items: center;

    img {
      max-width: 100%;
      max-height: 100%;
    }

    span {
      display: none;
      position: absolute;
      right: 0;
      top: 0;
      background-color: $failColor;
      height: 20px;
      width: 20px;
      font-size: 18px;
      color: #fff;
    }

    &:hover {
      span {
        display: flex;
        align-items: center;
        justify-content: center;
      }
    }
  }
}
</style>